package com.touchfired.server.controller;

import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.RoomInfo;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.event.impl.*;
import com.touchfired.common.core.publisher.impl.EventPublisher;
import com.touchfired.common.exception.ErrorCode;
import com.touchfired.common.exception.ServiceException;
import com.touchfired.common.params.CreateRoomParams;
import com.touchfired.common.params.RoomRespInfo;
import com.touchfired.common.utils.RoomUtil;
import com.touchfired.server.service.IClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

/**
 * 房间控制器
 * @author 幸佳俊
 */
@RestController
@RequestMapping(value = "/room")
public class RoomController {

    @Autowired
    private ServerContext serverContext;

    @Autowired
    private EventPublisher publisher;

    @GetMapping(value = "/list")
    public List<RoomRespInfo> getRoomInfoList() {
        return RoomUtil.converters(serverContext.getRooms());
    }

    @PostMapping(value = "/create")
    public RoomRespInfo createRoomInfo(@RequestBody CreateRoomParams roomParams) {
        String longId = roomParams.getLongId();
        ClientInfo clientInfo = serverContext.getClientInfo(longId);
        if (clientInfo == null) {
            throw new ServiceException(ErrorCode.CLIENT_NULL_ERROR);
        }
        RoomInfo roomInfo = (RoomInfo) publisher.publish(new RoomCreateEvent(clientInfo, roomParams));
        return RoomUtil.converter(roomInfo);
    }

    @GetMapping(value = "/quitRoom")
    public void quitRoom(@RequestParam("longId") String longId, @RequestParam("roomId") String roomId) {
        ClientInfo clientInfo = serverContext.getClientInfo(longId);
        if (clientInfo == null) {
            throw new ServiceException(ErrorCode.CLIENT_NULL_ERROR);
        }
        RoomInfo roomInfo = serverContext.getRoomInfo(roomId);
        if (roomInfo == null) {
            throw new ServiceException(ErrorCode.ROOM_NULL_ERROR);
        }
        publisher.publish(new RoomQuitEvent(clientInfo, roomInfo));
    }

    @GetMapping(value = "/joinRoom")
    public RoomRespInfo joinRoom(@RequestParam("longId") String longId, @RequestParam("roomId") String roomId) {
        ClientInfo clientInfo = serverContext.getClientInfo(longId);
        if (clientInfo == null) {
            throw new ServiceException(ErrorCode.CLIENT_NULL_ERROR);
        }
        RoomInfo roomInfo = serverContext.getRoomInfo(roomId);
        if (roomInfo == null) {
            throw new ServiceException(ErrorCode.ROOM_NULL_ERROR);
        }
        return (RoomRespInfo) publisher.publish(new RoomJoinEvent(clientInfo, roomInfo));
    }
}
